<?php
/**
 * Created by jinqiang on 2024/8/22 17:14.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Op;


use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;
use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Repository\FeishuRepository;
use Illuminate\Support\Facades\DB;

class LendsaleService
{
    public function search($param)
    {
        $conn = (new SsyAllocationSaleListTable());
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if($param['adduser'] ?? ""){
            $conn = $conn->where('adduser', $param['adduser']);
        }
        if($param['allocation_number'] ?? ""){
            $allocationNumbers = explode(",", str_replace("，", ",", $param['allocation_number']));
            $conn = count($allocationNumbers) > 1 ? $conn->whereIn('allocation_number', $allocationNumbers) : $conn->where('allocation_number', $param['allocation_number']);
        }
        if($param['createtime'] ?? []){
            $start = $param['createtime'][0]." 00:00:00";
            $end = $param['createtime'][1]." 23:59:59";
            $conn = $conn->whereBetween('createtime', [$start, $end]);
        }
        if($param['source_allocation_number'] ?? ""){
            $sourceAllocationNumbers = explode(",", str_replace("，", ",", $param['source_allocation_number']));
            $orders = (new SsyAllocationSaleTable())->whereIn('source_allocation_number', $sourceAllocationNumbers)->get(['allocation_number'])->toArray();
            if(empty($orders)){
                return ['data' => [], 'total' => 0];
            }
            $conn = $conn->whereIn('allocatoin_number', array_column($orders, 'allocation_number'));
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $allocationNumbers = array_column($res['data'], 'allocation_number');
        $approvalIdMap = [];//飞书审批ID
        $orderMap = [];//获取明细
        if(!empty($allocationNumbers)){
            $orders = (new SsyAllocationSaleTable())->whereIn('allocation_number', $allocationNumbers)->get()->toArray();
            foreach ($orders as $order){
                $orderMap[$order['allocation_number']][$order['sku_code']][] = [
                    'source_allocation_number' => $order['source_allocation_number'],
                    'num' => $order['num']
                ];
            }
            //飞书审批id
            $approvalList = (new SsyFeishuApprovalBindingTable())->whereIn('data_id', $allocationNumbers)->where('status', 1)
                ->get(['data_id', 'instance_code'])->toArray();
            foreach ($approvalList as $item){
                $approvalIdMap[$item['data_id']] = $item['instance_code'];
            }
        }

        foreach($res['data'] as &$item){
            unset($item['source_allocation_number']);
            $item['detail'] = [$orderMap[$item['allocation_number']]];
            $item['detail_header'] = array_keys($orderMap[$item['allocation_number']]);
            $item['approval_id'] = $approvalIdMap[$item['allocation_number']];
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function detail($allocationNumber)
    {
        $saleObj = (new SsyAllocationSaleListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
        $orders = (new SsyAllocationSaleTable())->where('allocation_number', $allocationNumber)
            ->get(['source_allocation_number', 'sku_code', 'num as plan_num', 'img', 'type_name', 'price'])->toArray();
        $lendMap = [];
        foreach($orders as &$order){
            $lendDetail = $lendMap[$order['source_allocation_number']] ?? [];
            if(empty($lendDetail)){
                $lendDetail = array_column((new LendService())->lendList($order['source_allocation_number']), null, 'sku_code');
                $lendMap[$order['source_allocation_number']] = $lendDetail;
            }
            $order['num'] = $lendDetail[$order['sku_code']]['num'];//计划借出
            $order['actually_num'] = $lendDetail[$order['sku_code']]['actually_num'];//实际借出数
            $order['actually_return_num'] = $lendDetail[$order['sku_code']]['actually_return_num'];//实际归还数
            $order['ipurchase_num'] = $lendDetail[$order['sku_code']]['ipurchase_num'];//已转内购数
            $order['give_num'] = $lendDetail[$order['sku_code']]['give_num'];//已转赠送数
            $order['sale_num'] = $lendDetail[$order['sku_code']]['sale_num'];//已转销售数
        }
        unset($order);
        $saleObj['list'] = $orders;
        return $saleObj;
    }

    public function approval($param)
    {
        $user = auth()->guard("api")->user()->toArray();
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        $sourceAllocationNumber = $detail[0]['allocation_number'];
        $sourceAllocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $sourceAllocationNumber)->first()->toArray();
        $isSubject = $sourceAllocationObj['is_subject'] ?: $user['is_subject'];
        $skuCodes = array_column($detail, 'sku_code');
        $allocationNumber = "JZX".$user['id'].date('YmdHis');
        //生成明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        $totalNum = 0;
        $tableStr = "";
        DB::beginTransaction();
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => '数量 错误'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "price" => (Double)($item['price'] ?: 0),
                "source_allocation_number" => $item['allocation_number'],
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationSaleTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            $totalNum += (Int)$item['num'];
            $tableStr .= '[{"id": "type_name","type":"input","value":"'.$jyMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'
                .$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$item['num'].'"},{"id":"price","type":"input","value":"'.$orderData['price']
                .'"},{"id":"source_allocation_number","type":"input","value":"' .$item['allocation_number'].'"}],';
        }
        $tableStr = rtrim($tableStr,',');
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "sku_code" => serialize($skuCodes),
            "adduser" => $user['name'],
            "num" => $totalNum,
            "source_allocation_number" => serialize(array_unique(array_column($detail, 'allocation_number'))),
            "is_subject" => $isSubject,
            "status" => 0,
            "reason" => $param['reason'],
            "createtime" => date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationSaleListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //发起飞书审批
        $date = date("Y-m-d\TH:i:s+H:00",time());
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$approvalSubject]['jzx_approval_code'];
        //$fsApprovalCode = "BB000E7D-F41B-4BF7-9E93-4E895008CE4A";//内部测试
        $subjectLabelMap = ["kz" => "mclipmqq-pg3hbdgero-0", "mz" => "mclipmqq-8ikp7k71xyr-0", "qyx" => "mclipmqq-u41qgh83xl-0"];
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"allocation_number","type":"input","value":"'.$allocationNumber.'"},{"id":"createtime","type":"date","value":"'
                .$date.'"},{"id":"groups","type":"input","value":"借出转销售"},{"id":"num","type":"number","value":"'
                .$totalNum.'"},{"id":"reason","type":"textarea","value":"'.$param['reason'].'"},{"id": "detaillist","type": "fieldList","value": ['.$tableStr.']}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建借转销,失败!'.($res['msg'] ?? ""), 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 10,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        DB::commit();
        return $createRes;
    }
}
